<?php

namespace App\Http\Service;

use Illuminate\Support\Facades\Config;
use App\Models\Qiniu;
use Illuminate\Http\Request;

class QiniuService
{
	private static $_obj;

	/**
	 * 单例模式
	 * @return object self
	 * @author  朱旭
	 */
	public static function getInstance()
	{
		if (!self::$_obj instanceof self) {
			self::$_obj = new self();
		}
		return self::$_obj;
	}

	public function __construct()
	{
		
	}

	/**
	 * 七牛云上传
	 * @param object request Request类
	 * @param string formName 上传文件表单名称
	 * @param array allowed_extensions 文件后缀
	 * @param booles single 是否为单文件上传
	 * @return array 状态码,描述,文件名称
	 * @author  朱旭
	 */
	public function qiniuUploads(Request $request, $formName, $allowed_extensions=['png', 'jpg', 'jpeg', 'gif'], $single=true)
	{
		$file = $request->file($formName);
		if (empty($file)) {
			return $this->returnArray(406, '表单为空');
		}
		$filePath = [];
		if ($single) {
			if (!$file->isValid()) {
				return $this->returnArray(307, '文件上传失败');
			}
			if (!$file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
				return $this->returnArray(301, "文件格式错误,可上传的文件后缀为".implode('，', $allowed_extensions));
			}
			$config = Config::get('config.qiniu');
			$qiniu = new Qiniu;
			list($ret, $err) = $qiniu->imge_upload($config['imge_policy']['cover'], $file);
			if ($err !== null) {
				$filePath[] = $ret['key'];
			}
		}else{
			foreach ($file as $key => $val) {
				if (!$val->isValid()) {
					return $this->returnArray(307, '文件上传失败');
				}
				if (!empty($val)) {
					if (!$val->getClientOriginalExtension() && !in_array($val->getClientOriginalExtension(), $allowed_extensions)) {
						return $this->returnArray(301, "文件格式错误,可上传的文件后缀为".implode('，', $allowed_extensions));
					}
					$config = Config::get('config.qiniu');
					$qiniu = new Qiniu;
					list($ret, $err) = $qiniu->imge_upload($config['imge_policy']['cover'], $val);
				    if ($err === null) {
				    	$filePath[] = $ret['key'];
				    }		
				}
			}
		}
		return $this->returnArray(200, '上传成功', $filePath);
	}

	private function returnArray($code=200, $message='操作成功' ,$data='')
	{
		return [
			'code' => $code,
			'data' => $data,
			'message' => $message
		];
	}
}